package com.will.txj.aj.security.config.auth;

import com.will.txj.common.result.R;
import com.will.txj.common.result.RC;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: wen-yi;
 * @date: 2021/12/5 21:48;
 * @Description: 登录失败处理
 */
@Component("myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        R r = null;
        if (e instanceof AccountExpiredException){
            r = R.fail(RC.USER_ACCOUNT_EXPIRED);
        } else if (e instanceof BadCredentialsException){
            r = R.fail(RC.USER_CREDENTIALS_ERROR);
        } else if (e instanceof CredentialsExpiredException){
            r = R.fail(RC.USER_CREDENTIALS_EXPIRED);
        } else if (e instanceof DisabledException){
            r = R.fail(RC.USER_ACCOUNT_DISABLE);
        } else if (e instanceof LockedException){
            r = R.fail(RC.USER_ACCOUNT_LOCKED);
        } else if(e instanceof InternalAuthenticationServiceException){
            r = R.fail(RC.USER_ACCOUNT_NOT_EXIST);
        } else if(e instanceof ValidateCodeException){
            r = R.fail(RC.USER_VERIFY_CODE_EXPIRED);
        } else {
            r = R.fail();
        }
        JSONAuthenticationUtil.WriteJSON(request, response, r);
    }
}
